var gride=new Array();
var score=0;
var hasConfig=new Array();
var documentWidth=window.screen.availWidth;
var documentHieght=window.screen.availHeight;
var grideContainerWidth=0.92*documentWidth;
var cellSideLength=0.18*documentWidth;
var cellSidePadding=0.04*documentWidth;
var startX=0;
var startY=0;
var endX=0;
var endY=0;

$(document).ready(function(e) {
	 prepareForMobile();
     newgame();
	 $(document).keyup(function(e){
	       
		   switch(e.which){
		        case 37:
				    e.preventDefault();
				    if(moveLeft()){
				         setTimeout(getOneNum,210);
						 setTimeout(isMoveOver,300);
					}
					break;
				case 38:
				    e.preventDefault();
				    if(moveTop()){
					     setTimeout(getOneNum,210)
						setTimeout(isMoveOver,300);
					}
				    break;
				case 39:
				    e.preventDefault();
				    if(moveRight()){
					     setTimeout(getOneNum,210)
						 setTimeout(isMoveOver,300);
					}
					break;
				case 40:
				    e.preventDefault();
				    if(moveBottom()){
						setTimeout(getOneNum,210)
						setTimeout(isMoveOver,300);
					}
					break;
				
		   }
	 });
});

myAddEvent(document,'touchstart',touchStart)
myAddEvent(document,'touchend',touchEnd)
myAddEvent(document,'touchmove',function(ev){
     ev.preventDefault();//防止手机滑动时会转向其他页面去，这是有的手机会有的默认效果
})

function touchStart(e){
	 startX=e.touches[0].pageX;
	 startY=e.touches[0].pageY;
}

function touchEnd(e){
     endX=e.changedTouches[0].pageX;
	 endY=e.changedTouches[0].clientY;
	 doAction();
}

function doAction(){
     var disX=endX-startX;
	 var disY=endY-startY;
	 
	 if(Math.abs(disX)<0.3*documentWidth&&Math.abs(disY)<0.3*documentWidth)
	       return;
	 if(Math.abs(disX)>=Math.abs(disY)){
	        if(disX>0){
			// moveright
			     if(moveRight()){
					     setTimeout(getOneNum,210)
						 setTimeout(isMoveOver,300);
				 }
			}else{
			//    moveLeft
			     if(moveLeft()){
				     setTimeout(getOneNum,210);
					 setTimeout(isMoveOver,300);
				}
			}
	 }else{
	         if(disY>0){
			 //    movebottom
			       if(moveBottom()){
						setTimeout(getOneNum,210)
						setTimeout(isMoveOver,300);
					}
			 }
			 else{
			 //    movetop
			        if(moveTop()){
					     setTimeout(getOneNum,210)
						setTimeout(isMoveOver,300);
					}
			 }
	 }
}

function myAddEvent(obj,Event,fn){
      if(obj.attachEvent){
	        obj.attachEvent('on'+Event,fn);
	  }else{
	        obj.addEventListener(Event,fn,false);
	  }
}

function prepareForMobile(){
	
	 if(documentWidth>500){
		   documentWidth=500;
	       grideContainerWidth=500;
		   cellSideLength=100;
		   cellSidePadding=20;
	 }
	 
     $('.num-div').css({
	      'width':(grideContainerWidth-2*cellSidePadding)+'px',
		  'height':(grideContainerWidth-2*cellSidePadding),
		  'padding':cellSidePadding,
		  'border-radius':0.02*grideContainerWidth
	 })
	 
	 $('.num-cell').css({
	       'width':cellSideLength,
		   'height':cellSideLength,
		   'border-radius':0.1*cellSideLength
	 })
}

function isMoveOver(){
     if(noPlace(gride)&&noMove()){
	      alert('gameover')
		  newgame();
	 }
}

function noMove(){
     if(moveLeft()||moveTop()||moveBottom()||moveRight()){
		  return false;
	}
	 return true;
}

function newgame(){
     init();
	 getOneNum();
	 getOneNum();
}

function init(){
	 //$('.num-div').remove('.gride-cell');
     for(var i=0; i<4; i++){
	      for(var j=0; j<4; j++){
		       var element=$('#num-cell-'+i+'-'+j);
			   element.css('top',getTop(i));
			   element.css('left',getLeft(j));
		  }
	 }
	 
	 for(var i=0; i<4; i++){
	      gride[i]=new Array();
		  hasConfig[i]=new Array();
		  for(var j=0; j<4; j++){
		      gride[i][j]=0;
			  hasConfig[i][j]=false;
		  }
	 }
	 
	 updateNum();
	 $('span').text('score:'+0);
	 
	 for(var i=0; i<4; i++){
	      for(var j=0; j<4;j++){
		       $('.num-div').append('<div class="gride-cell" id="gride-cell-'+i+'-'+j+'"></div>');
			   var grideCell=$('#gride-cell-'+i+'-'+j);
			   if(gride[i][j]==0){
			         grideCell.css('width','0px');
					 grideCell.css('height','0px');
					 grideCell.css('top',getTop(i)+cellSideLength/2);
					 grideCell.css('left',getLeft(j)+cellSideLength/2);
			   }else{
			         grideCell.css('width','100px');
					 grideCell.css('height','100px');
					 grideCell.css('top',getTop(i));
					 grideCell.css('left',getLeft(j));
					 grideCell.css('background-color',getNumBgColor(gride[i][j]));
					 grideCell.css('color',getNumColor(gride[i][j]));
					 grideCell.text(gride[i][j]);
			   }
		  }
	 }
}

function getOneNum(){
	 
	 if(noPlace(gride)){
	      return false;
	 }
     var randX=parseInt(Math.floor(Math.random()*4));
	 var randY=parseInt(Math.floor(Math.random()*4));
	 /*while(true){
	      if(gride[randX][randY]==0){
		        break;
		  }
		  randX=parseInt(Math.floor(Math.random()*4));
		  randY=parseInt(Math.floor(Math.random()*4));
	 }*///计算机查可能查找很久才找到那个特定的位置；所以我们可以人工来
	 var time=0;
	 while(time<50){
		  if(gride[randX][randY]==0){
		        break;
		  }
		  randX=parseInt(Math.floor(Math.random()*4));
		  randY=parseInt(Math.floor(Math.random()*4));
		  time++;
	 }
	 
	 if(time==50){
	      for(var i=0; i<4; i++){
		       for(var j=0;j<4;j++){
			         if(gride[i][j]==0){
					    randX=i;
						randY=j;
					 }
			   }
		  }
	 }
	 
	 var randNum=Math.random()>0.5? 2:4;
	 gride[randX][randY]=randNum;
	 gameAnimation(randX,randY,randNum);
}

function moveLeft(){
      if(!canMoveLeft(gride)){
	        return false;
	  }
	  for(var i=0; i<4;i++){
	       for(var j=1; j<4;j++){
		         if(gride[i][j]!=0){
				      for(var k=0;k<j;k++){
					       
						   if(gride[i][k]==0&& pointNoThing(i,k,j,gride)){
						         updateNewNumAnimate(i,j,i,k,gride);
								 gride[i][k]=gride[i][j];
								 gride[i][j]=0;
								 break;     
						   } else if(gride[i][k]==gride[i][j]&&pointNoThing(i,k,j,gride)&&!hasConfig[i][j]){
						         updateNewNumAnimate(i,j,i,k,gride);
								 gride[i][k]+=gride[i][j];
								 gride[i][j]=0;
								 score+=gride[i][k];
								 hasConfig[i][j]=true;
								 getScore();
								 break;
						   }
						   
					  }
				 }
		   }
	  }
	  setTimeout(updateNum,200);
	  return true;
	  
}

function moveTop(){
     if(!canMoveTop()){
	       return false;
	 } 
	 
	 for(var i=1; i<4; i++)
	      for(var j=0; j<4; j++)
		      if(gride[i][j]!=0)
			      for(var k=0; k<i; k++)
				      if(gride[k][j]==0&&pointTopNoThing(i,k,j)){
					        updateNewNumAnimate(i,j,k,j);
							gride[k][j]=gride[i][j];
							gride[i][j]=0;
							break;
					  }else if( gride[k][j]==gride[i][j]&&pointTopNoThing(i,k,j)&&!hasConfig[i][j]){
					        updateNewNumAnimate(i,j,k,j);
							gride[k][j]+=gride[i][j];
							gride[i][j]=0;
							score+=gride[k][j];
							hasConfig[i][j]=true;
							getScore();
							break;
					  }
	 setTimeout(updateNum,200);
	 return true;
}

function moveRight(){
     if(!canMoveLeft())
	     return false;
	 for(var i=0; i<4;i++)
	     for(var j=0; j<3;j++)
		     if(gride[i][j]!=0)
			     for(var k=3; k>j; k--)
				     if(gride[i][k]==0&&pointRightNoThing(i,k,j)){
					       updateNewNumAnimate(i,j,i,k);
						   gride[i][k]=gride[i][j];
						   gride[i][j]=0;
						   break;
					 }else if(gride[i][k]==gride[i][j]&&pointRightNoThing(i,k,j)&&!hasConfig[i][j]){
					       updateNewNumAnimate(i,j,i,k);
						   gride[i][k]+=gride[i][j];
						   gride[i][j]=0;
						   score+=gride[i][k];
						   hasConfig[i][j]=true;
						   getScore();
						   break;
					 }
	 setTimeout(updateNum,200);
	 return true;
	 
}

function moveBottom(){
      if(!canMoveBottom()){
		   return false; 
	  }
	  for(var i=0; i<3; i++)
	     for(var j=0;j<4;j++)
		    if(gride[i][j]!=0)
			    for( var k=3; k>i; k--)
				   if(gride[k][j]==0&&pointBottomNoThing(i,k,j)){
				           updateNewNumAnimate(i,j,k,j);
						   gride[k][j]=gride[i][j];
						   gride[i][j]=0;
						   break;
					}else if(gride[k][j]==gride[i][j]&&pointBottomNoThing(i,k,j)&&!hasConfig[i][j]){
					       updateNewNumAnimate(i,j,k,j);
						   gride[k][j]+=gride[i][j];
						   gride[i][j]=0;
						   score+=gride[k][j];
						   hasConfig[i][j]=true;
						   getScore();
						   break;
					}
	 setTimeout(updateNum,200);
	 return true;
}

function getScore(){
    
	 $('span').text('score:'+score);
}